package com.rabbitmq.ChattingRoom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.rabbitmq.ChattingRoom.service.UserService;
import com.rabbitmq.ChattingRoom.service.mapper.UserMapper;
import com.rabbitmq.ChattingRoom.util.Entity.User;
import com.rabbitmq.ChattingRoom.util.common.req.UserRegisterReq;
import com.rabbitmq.ChattingRoom.util.common.resp.UserRESP;
import com.rabbitmq.ChattingRoom.util.utils.BeanUtil;
import com.rabbitmq.ChattingRoom.util.utils.MD5Util;
import com.rabbitmq.ChattingRoom.util.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public Integer register(UserRegisterReq req) {
        if (isExistName(req.getUsername()))
            return -1;
        User user = BeanUtil.copyProperties(req, User.class);
        user.setSalt(StringUtil.saltGenerator(5));
        String password = MD5Util.encrypt(req.getPassword(), user.getSalt());

        user.setId(IdWorker.getId());
        user.setPassword(password);
        user.setStatus(0);
        return userMapper.insert(user);
    }

    @Override
    public boolean isExistName(String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername,username);
        return userMapper.selectCount(wrapper) > 0;
    }

    @Override
    public boolean isExistId(Long id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getId,id);
        return userMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public List<UserRESP> getUsers() {
        return userMapper.getUsers();
    }

    @Override
    public List<UserRESP> getUsersByRoomId(Long roomId) {
        return userMapper.getUsersByRoomId(roomId);
    }

    @Override
    public int UpdateUser(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public User selectUserByName(String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername,username);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public User selectUserById(Long id) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getId,id);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public User selectUserByNickname(String nickname) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getNickname,nickname);
        return userMapper.selectOne(wrapper);
    }
}
